<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            //进行后序遍历 找出叶子节点
            var lowestCommonAncestor = function (root, p, q) {
                if (!root) return null
                //遍历到最后的叶子节点，如果它等于p和q，就return
                if (root == p || root == q) return root
                let left = lowestCommonAncestor(root.left, p, q)
                //left和right得到的是当前root节点的左右子节点
                let right = lowestCommonAncestor(root.right, p, q)
                if (left && right) {
                    return root
                }
                //只要叶子节点中p存在了，left就一直是p
                if (left) {
                    return left
                }
                if (right) {
                    return right
                }
            }
            let tree = {
                val: 1,
                left: {
                    val: 2,
                    left: {
                        val: 4,
                        left: {
                            val: 8,
                        },
                    },
                    right: {
                        val: 5,
                    },
                },
                right: {
                    val: 3,
                    left: {
                        val: 6,
                    },
                    right: {
                        val: 7,
                        left: {
                            val: 9,
                        },
                    },
                },
            }
            /* 后序遍历 还有返回值 */
            function postOrder(tree) {
                if (!tree || tree.val == p || tree.val == q) {
                    return tree
                }
                /* 
                它一直遍历到叶子节点
                */
                let left = postOrder(tree.left)
                let right = postOrder(tree.right)
            }
            postOrder(tree)
        </script>
    </body>
</html>
